/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pmc.dwa.common.utils.Escape;
import com.pmc.dwa.common.utils.JsonGrid;
import com.pmc.dwa.common.utils.PaginationSupport;
import com.pmc.dwa.security.model.TUser;
import com.pmc.dwa.security.model.TUserDetails;
import com.pmc.dwa.security.service.IUserService;
import com.pmc.dwa.security.utils.EncryptUtils;
import com.pmc.dwa.security.utils.SpringSecurityUtils;

/**
 * @description  用户管理 
 * @author aokunsang
 * @date 2013-1-8
 */
@Controller
@RequestMapping("/rbac")
public class UserController {

	@Autowired
	private IUserService userService;
	
	/* 获取用户列表*/
	@RequestMapping(value="getPagesTUser",method={RequestMethod.POST})
	public @ResponseBody JsonGrid<TUser> getPagesTUser(
			@RequestParam(required=true) Integer page,
			@RequestParam(required=true) Integer rows,
			String queryname){
		TUserDetails userInfo = SpringSecurityUtils.getCurrentUser();
		PaginationSupport<TUser> pager = userService.getPagesTUser(userInfo.getId(), queryname, page, rows);
		long totalCount = pager.getTotalCount();
		List<TUser> list = pager.getItems()==null?new ArrayList<TUser>():pager.getItems();
		for(Iterator<TUser> iter = list.iterator();iter.hasNext();){
			TUser tUser = iter.next();
			tUser.setUserRoles(userService.findUserRolesByUsername(tUser.getUsername()));
			tUser.setSection(userService.findValidSection(userService.findSectionByUid(tUser.getId())));
		}
		return new JsonGrid<TUser>(totalCount, list);
	}
	/* 根据字段和值判断其有效性*/
	@RequestMapping(value="chkUserProperty",method={RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody Boolean chkUserProperty(
			@RequestParam(required=true)String chkColumn,
			@RequestParam(required=true)String colname){
		return !userService.chkDataByCol(chkColumn, colname);
	}
	/* 获取用户信息*/
	@RequestMapping(value="getUser/{userid}")
	public @ResponseBody TUser getUser(@PathVariable String userid){
		TUser tuser = userService.findUserByid(userid);
		if(tuser==null) return new TUser();
		tuser.setPassword("");
		tuser.setSection(userService.findSectionByUid(userid));
		tuser.setUserRoles(userService.findUserRolesByUsername(tuser.getUsername()));
		return tuser;
	}
	/* 更新用户状态*/
	@RequestMapping(value="setUserStatus",method={RequestMethod.POST})
	public @ResponseBody String setUserStatus(String uid,String statVal){
		if(StringUtils.isEmpty(uid)){
			return "{success:0,msg:'"+Escape.escape("提供资料不全，无法更新用户状态。")+"'}";
		}
		if(statVal==null || (!"0".equals(statVal) && !"1".equals(statVal))){
			return "{success:0,msg:'"+Escape.escape("错误的状态值")+"'}";
		}
		try {
			userService.editUserColumnVal(uid, "STATUS", statVal);
			return "{success:1}";
		} catch (Exception e) {
			return "{success:0,msg:'"+e.getMessage()+"'}";
		}
	}
	
	/* 更新用户信息*/
	@RequestMapping(value="editUser",method=RequestMethod.POST)
	public @ResponseBody String editUser(TUser user,String section_id,String role_id,String password_confirm){
		
		if(user==null || StringUtils.isEmpty(user.getId())){
			return "{success:false,msg:'"+Escape.escape("提供资料不全，请重试修改。")+"'}";
		}
		if(StringUtils.isNotEmpty(password_confirm) && StringUtils.isNotEmpty(user.getPassword())
					&& !password_confirm.equals(user.getPassword())){
			return "{success:false,msg:'"+Escape.escape("密码和确认密码不是同一个。")+"'}";
		}
		try {
			String[] aryRoleid = new String[1];
			String[] arySectionid = new String[1];
			aryRoleid[0] = role_id; arySectionid[0] = section_id;
			if(StringUtils.isNotEmpty(password_confirm)){
				user.setPassword(EncryptUtils.md5(password_confirm));
			}else{
				user.setPassword(SpringSecurityUtils.getCurrentUser().getPassword());  //设置为当前密码
			}
			user.setUpt_time(new Timestamp(System.currentTimeMillis()));
			userService.editUser(user, arySectionid, aryRoleid);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	
	/* 添加用户信息*/
	@RequestMapping(value="addUser",method=RequestMethod.POST)
	public @ResponseBody String addUser(TUser user,String section_id,String role_id,String password_confirm){
		
		if(user==null){
			return "{success:false,msg:'"+Escape.escape("系统出错，请稍后重试。")+"'}";
		}
		if(StringUtils.isNotEmpty(password_confirm) && StringUtils.isNotEmpty(user.getPassword())
				&& !password_confirm.equals(user.getPassword())){
			return "{success:false,msg:'"+Escape.escape("密码和确认密码不是同一个。")+"'}";
		}
		try {
			String[] aryRoleid = new String[1];
			String[] arySectionid = new String[1];
			aryRoleid[0] = role_id; arySectionid[0] = section_id;
			user.setId(UUID.randomUUID().toString());
			user.setPassword(EncryptUtils.md5(password_confirm));
			user.setStatus((byte)1);
			user.setReg_time(new Timestamp(System.currentTimeMillis()));
			userService.addUser(user, arySectionid, aryRoleid);
			return "{success:true,msg:''}";
		} catch (Exception e) {
			return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
		}
	}
	/**
	 * 删除用户
	 * @param uid
	 * @return
	 */
	@RequestMapping(value="delUser/{uid}",method=RequestMethod.POST)
	public @ResponseBody String delUser(@PathVariable String uid){
		try {
			userService.delUser(uid);
			return "{success:true,msg:'删除成功!'}";
		} catch (Exception e) {
			e.printStackTrace();
			return "{success:false,msg:'"+e.getMessage()+"'}";
		}
	}
}
